<?php
class STranslateableBehavior extends CActiveRecordBehavior {

    /**
     * Apply translated attributes to current lang 
     * 
     * @access public
     */
    public function afterFind($event)
    {
    	$lang_default = Yii::app()->params['language_default'];
    	if(isset($_GET['lang']) && $_GET['lang']!=$lang_default){
	        $forTranslate = $this->owner->translate();
			if (sizeof($forTranslate) > 0)
			{
			$table = $this->owner->tableName();
			$lang = Yii::app()->language;
			$priKey = $this->owner->primarykey;
			$Trans = $this->getTranslated($table, $lang, $priKey);
			$data = unserialize($Trans);
				foreach($forTranslate as $attr)
				{
					if (is_array($data))
						$this->owner->$attr = $data["$attr"];
				}
			}
    	}
    }
	public function getTranslated($table, $lang, $priKey)
	{
		$sql="SELECT trans_content FROM tbl_translates WHERE published=1 AND language=:p AND table_name=:d AND pri_id=:i";
		$command = Yii::app()->db->createCommand($sql);
		$command->bindParam(':p', $lang, PDO::PARAM_STR);
		$command->bindParam(':d', $table, PDO::PARAM_STR);
		$command->bindParam(':i', $priKey, PDO::PARAM_INT);
		return $command->queryScalar();
	}
}
